package com.ziJin.service.impl;

import com.ziJin.mapper.StudentMapper;
import com.ziJin.pojo.Student;
import com.ziJin.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Override
    @Cacheable(value = "student", key = "#id", unless = "#result == null")
    public Student getInfo(Integer id) {
        return studentMapper.getInfo(id);
    }

    @Override
    @Cacheable(value = "students", key = "'all'")
    public List<Student> findAll() {
        return studentMapper.findAll();
    }

    @Override
    @Caching(evict = {
        @CacheEvict(value = "student", key = "#id"),
        @CacheEvict(value = "students", key = "'all'")
    })
    public void deleteById(Integer id) {
        studentMapper.deleteById(id);
    }

    @Override
    @CacheEvict(value = "students", key = "'all'")
    public void save(Student student) {
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.save(student);
    }

    @Override
    @Caching(evict = {
        @CacheEvict(value = "student", key = "#student.id"),
        @CacheEvict(value = "students", key = "'all'")
    })
    public void update(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.update(student);
    }

    @Override
    public List<Student> findByInfo(String studentNum, String name) {
        return studentMapper.findByInfo(studentNum, name);
    }

}
